class WebSocketClient {
  constructor(url) {
    this.socket = new WebSocket(url);
    this.callbacks = {
      onMessage: [],
      onOpen: [],
      onClose: [],
      onError: [],
    };
    //监听方法
    this.socket.onmessage = (event) => {
      this.callbacks.onMessage.forEach((callback) => callback(event.data));
    };

    this.socket.onopen = (event) => {
      this.callbacks.onOpen.forEach((callback) => callback(event));
    };

    this.socket.onclose = (event) => {
      this.callbacks.onClose.forEach((callback) => callback(event));
    };

    this.socket.onerror = (event) => {
      this.callbacks.onError.forEach((callback) => callback(event));
    };
  }

  onMessage(callback) {
    this.callbacks.onMessage.push(callback);
  }

  onOpen(callback) {
    this.callbacks.onOpen.push(callback);
  }

  onClose(callback) {
    this.callbacks.onClose.push(callback);
  }

  onError(callback) {
    this.callbacks.onError.push(callback);
  }
  //发送
  send(message) {
    if (this.socket.readyState === WebSocket.OPEN) {
      this.socket.send(message);
    } else {
      console.error("WebSocket is not open.");
    }
  }

  close() {
    this.socket.close();
  }
}

export default WebSocketClient;
